package org.glut.wechat.personalcenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.glut.wechat.personalcenter.domain.LoginResult;
import org.glut.wechat.personalcenter.domain.RegisterResult;
import org.glut.wechat.personalcenter.domain.User;
import org.glut.wechat.personalcenter.service.IUserService;
import org.glut.wechat.personalcenter.util.AliOSSUtils;
import org.glut.wechat.personalcenter.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户表 前端控制器
 *
 * @author bin
 * @since 2025-08-18 11:24
 */
@RestController
@Slf4j
@RequestMapping("/user")
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST}, allowedHeaders = "*")
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private AliOSSUtils aliOSSUtils;
    /*查询用户信息*/
    @GetMapping("/GetUserInfo")
    public ResponseEntity<User> getUserInfo(@RequestParam Integer userId) {
        System.out.println("接收的userId：" + userId); // 确认参数是否正确传递
        return ResponseEntity.ok().body(userService.getById(userId));
    }

    /*更新用户信息*/
    @PostMapping("/UpdateUserInfo")
    public ResponseEntity<User> updateUserInfo(@RequestBody User user) {
        if (userService.updateById(user)) {
            User respUser = userService.getById(user.getId());
            return ResponseEntity.ok().body(respUser);
        }

        return ResponseEntity.badRequest().body(null);
    }
    /*更新头像*/
    @PostMapping("/uploadAvatar")
        public ResponseEntity<String> uploadAvatar(Integer userId, MultipartFile image) throws IOException {
             log.info("文件上传，文件名：{}",image.getOriginalFilename());

             String url = aliOSSUtils.upload(image);
             log.info("文件上传完成，访问URL：{}", url);

             User user = new User();
             user.setId(userId);
             user.setAvatar(url);

        if (userService.updateById(user)) {
            return ResponseEntity.ok().body("头像更新成功");
        } else {
            return ResponseEntity.badRequest().body("头像更新失败");
        }
        }

    /*删除用户*/
    @DeleteMapping("deleteUser")
    public ResponseEntity<String> deleteUser(Integer userId) {
      if (userService.removeById(userId)) {
          return ResponseEntity.ok().body("用户删除成功");
      }

        // 删除失败的情况
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("用户删除失败，请稍后重试");
      }

    /*用户密码登录*/
    @PostMapping("/PasswordLogin")
    public ResponseEntity<Map<String, Object>> passwordLogin(@RequestBody User user) {
        LoginResult resp = userService.passwordLogin(user.getPhone(), user.getPassword());

        if (resp.getCode() == 0) {
            String token = jwtUtil.generateToken(resp.getUser().getId());

            // 构造包含 data.token 的响应
            Map<String, Object> response = new HashMap<>();
            response.put("code", 0);
            response.put("msg", "登录成功");
            response.put("data", new HashMap<>() {{
                put("token", token); // token 放到 data 里
                put("user", resp.getUser());
            }});

            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.ok(Map.of(
                    "code", resp.getCode(),
                    "msg", resp.getMsg()
            ));
        }
    }
    /*用户短信登录*/
    @PostMapping("/SmsLogin")
    public ResponseEntity<LoginResult> smsLogin(@RequestBody User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        User respUser = userService.getOne(queryWrapper);

        // 用户不存在
        if (respUser == null) {
            LoginResult errorResp = new LoginResult();
            errorResp.setCode(1);
            errorResp.setMsg("用户不存在");
            return ResponseEntity.ok().body(errorResp);
        }

        // 成功响应
        LoginResult successResp = new LoginResult();
        successResp.setCode(0);
        successResp.setMsg("登录成功");
        successResp.setUser(respUser);

        // 生成Token并返回
        String token = jwtUtil.generateToken(respUser.getId());
        System.out.println("短信登录生成的token:"+token);
        return ResponseEntity.ok()
                .header("Authorization", "Bearer " + token)
                .body(successResp);
    }

    /*用户注册 */
    @PostMapping("/Register")
    public ResponseEntity<RegisterResult> register(@RequestBody User user) {
        // 检查手机号唯一性
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        if (userService.getOne(queryWrapper) != null) {
            RegisterResult errorResp = new RegisterResult();
            errorResp.setCode(1);
            errorResp.setMsg("用户已存在");
            return ResponseEntity.ok().body(errorResp);
        }

        // 生成随机用户名，小于6位，自动在前面补零
        String randomUsername = "微信" + String.format("%06d", (int) (Math.random() * 1000000));
        user.setUsername(randomUsername);

        if (userService.save(user)) {
            User respUser = userService.getOne(queryWrapper);
            System.out.println("注册成功，用户ID：" + respUser.getId());
            RegisterResult successResp = new RegisterResult();
            successResp.setCode(0);
            successResp.setMsg("注册成功");
            successResp.setUser(respUser);
            String token = null;
            try {
                // 生成Token并打印
                 token = jwtUtil.generateToken(respUser.getId());
                System.out.println("注册生成的token：" + token); // 关键打印
            } catch (Exception e) {
                System.out.println("生成token失败，异常信息：" + e.getMessage()); // 捕获异常
                e.printStackTrace(); // 打印堆栈信息，方便排查
            }
            return ResponseEntity.ok()
                    .header("Authorization", "Bearer " + token)
                    .body(successResp);
        }

        RegisterResult errorResp = new RegisterResult();
        errorResp.setCode(2);
        errorResp.setMsg("注册失败");
        return ResponseEntity.internalServerError().body(errorResp);
    }
}
